package com.csyf.manager.controller.system;

import com.csyf.manager.common.CommonConst;
import com.csyf.manager.entity.SysRole;
import com.csyf.manager.entity.SysUser;
import com.csyf.manager.service.SysRoleService;
import com.csyf.manager.service.SysUserService;
import com.csyf.manager.utils.ResultEntity;
import com.csyf.manager.utils.ResultUtli;
import com.csyf.manager.utils.page.JqGridVo;
import com.csyf.manager.vo.ChangePasswordVo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.xml.transform.Result;
import java.util.*;

/**
 * @Author: casper
 * @Description: 用户管理
 * @Date: Created in 2018/11/22 12:00
 */
@Controller
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 用户列表
     * @param vo
     * @param page
     * @param rows
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public JqGridVo list(SysUser vo, Integer page, Integer rows) {
        return sysUserService.queryUserList(vo, page, rows);
    }

    /**
     * 新增用户
     * @param userForm
     * @param confirmPwd
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public ResultEntity add(SysUser userForm, String confirmPwd) {
        String username = userForm.getUserName();
        SysUser user = sysUserService.selectByUsername(username);

        //验证用户名是否存在
        if (null != user) {
            return ResultUtli.DEFAULT_ERROR("用户名已存在！");
        }

        String password = userForm.getPassword();
        if (StringUtils.isNotBlank(confirmPwd) && StringUtils.isNotBlank(password)) {
            if (!confirmPwd.equals(password)) {
                return ResultUtli.DEFAULT_ERROR("两次密码输入不一致！");
            }
        }

        Date date = new Date();
        userForm.setCreateTime(date);
        userForm.setModifyTime(date);
        userForm.setStatus(CommonConst.STATUS_VALID.toString());
        userForm.setLastLoginTime(date);

        int num = sysUserService.addUser(userForm);
        if (num > 0) {
            return ResultUtli.DEFAULT_SUCCESS("添加用户成功", null);
        } else {
            return ResultUtli.DEFAULT_ERROR("添加用户失败");
        }
    }

    /**
     * 编辑用户详情
     * @param model
     * @param userId
     * @return
     */
    @GetMapping("/edit")
    public String userDetail(Model model, String userId) {
        SysUser user = sysUserService.selectByUserId(userId);
        model.addAttribute("user", user);
        return "user/userDetail";
    }

    /**
     * 编辑用户
     * @param userForm
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public ResultEntity editUser(SysUser userForm) {
        int num  = sysUserService.updateByUserId(userForm);
        if (num > 0) {
            return ResultUtli.DEFAULT_SUCCESS("编辑用户成功", null);
        } else {
            return ResultUtli.DEFAULT_ERROR("编辑用户失败");
        }
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @GetMapping("/delete")
    @ResponseBody
    public ResultEntity deleteUser(String userId) {
        List<String> userIdsList = Arrays.asList(userId);
        int num = sysUserService.updateStatusBatch(userIdsList, CommonConst.STATUS_INVALID);
        if (num > 0) {
            return ResultUtli.DEFAULT_SUCCESS("删除用户成功", null);
        } else {
            return ResultUtli.DEFAULT_ERROR("删除用户失败");
        }
    }

    /**
     * 批量删除用户
     * @param userIdStr
     * @return
     */
    @GetMapping("/batch/delete")
    @ResponseBody
    public ResultEntity batchDeleteUser(String userIdStr) {
        String[] userIds = userIdStr.split(",");
        List<String> userIdsList = Arrays.asList(userIds);
        int num = sysUserService.updateStatusBatch(userIdsList, CommonConst.STATUS_INVALID);
        if (num > 0) {
            return ResultUtli.DEFAULT_SUCCESS("删除用户成功", null);
        } else {
            return ResultUtli.DEFAULT_ERROR("删除用户失败");
        }
    }

    /**分配角色列表查询*/
    @PostMapping("/assign/role/list")
    @ResponseBody
    public Map<String,Object> assignRoleList(Long userId){
        List<SysRole> roleList = sysRoleService.selectRoles(new SysRole());
        Set<String> hasRoles = sysRoleService.findRoleByUserId(userId);
        Map<String, Object> jsonMap = new HashMap<>(2);
        jsonMap.put("rows", roleList);
        jsonMap.put("hasRoles",hasRoles);
        return jsonMap;
    }

    /**保存分配角色*/
    @PostMapping("/assign/role")
    @ResponseBody
    public ResultEntity assignRole(Long userId, String roleIdStr){
        try {
            String[] roleIds = roleIdStr.split(",");
            List<String> roleIdsList = Arrays.asList(roleIds);
            sysUserService.addAssignRole(userId,roleIdsList);
            List<String> userIds = new ArrayList<>();
            userIds.add(userId.toString());

            return ResultUtli.DEFAULT_SUCCESS("分配角色成功", null);
        } catch (Exception e) {
            return ResultUtli.DEFAULT_ERROR("分配角色失败");
        }
        //myShiroRealm.clearAuthorizationByUserId(userIds);
    }

    /**
     * 修改密码
     * @param changePasswordVo
     * @return
     */
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity changePassword(ChangePasswordVo changePasswordVo) {
        String oldPwd = changePasswordVo.getOldPassword();
        String newPwd = changePasswordVo.getNewPassword();
        String confirmPwd = changePasswordVo.getConfirmNewPassword();
        if (!newPwd.equals(confirmPwd)) {
            return ResultUtli.DEFAULT_ERROR("两次密码输入不一致！");
        }

        SysUser shiroUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        SysUser loginUser = sysUserService.selectByUserId(shiroUser.getUserId().toString());

        SysUser newUser = new SysUser();
        if (oldPwd.equals(loginUser.getPassword())) {
            newUser.setPassword(newPwd);
            newUser.setUserId(loginUser.getUserId());
            sysUserService.updatePwdByUserId(newUser);
        } else {
            return ResultUtli.DEFAULT_ERROR("您输入的旧密码有误！");
        }
        return ResultUtli.DEFAULT_SUCCESS("修改密码成功", null);

    }









}
